package com.lsq.tucao.express.service.serviceImpl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lsq.tucao.express.bean.po.Picture;
import com.lsq.tucao.express.dao.PictureMapper;
import com.lsq.tucao.express.response.JsonResult;
import com.lsq.tucao.express.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class PictureServiceImpl implements PictureService {

    @Autowired
    private PictureMapper pictureMapper;

    @Override
    public JsonResult postPicture(Long pictureId, String title, String content, MultipartFile pictureFile) throws IOException {
        if(pictureId != null && !StringUtils.isEmpty(title) && !StringUtils.isEmpty(content)){
            UpdateWrapper<Picture> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(Picture::getId,pictureId)
                    .set(Picture::getTitle,title)
                    .set(Picture::getContent,content);

            if(pictureFile != null){
                byte[] bytes = pictureFile.getBytes();
                updateWrapper.lambda().set(Picture::getPicture,bytes);
            }

            int update = pictureMapper.update(null, updateWrapper);
            if(update > 0){
                return new JsonResult(200,"轮播图修改成功");
            }else {
                return new JsonResult(500,"轮播图修改失败");
            }

        }else {
            return new JsonResult(500,"请填写标题和内容");
        }
    }

    @Override
    public Picture getPictureById(Long id) {
        Picture picture = pictureMapper.selectById(id);
        if(picture != null){
            return picture;
        }else {
            return null;
        }
    }

    @Override
    public JsonResult getAllPicture() {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        List<Picture> pictures = pictureMapper.selectList(queryWrapper);
        if(pictures != null && pictures.size() == 3){
            return new JsonResult(pictures,200,"获取所有图片信息成功");
        }else {
            return new JsonResult(500,"获取所有图片信息失败，图片数据为空或图片数量不为3");
        }
    }

}
